#pragma once
#include<iostream>
#include<assert.h>
#include<vector>
using namespace std;

enum Colour
{
	RED,
	BLACK
};

template<class T>   //data是一个泛型
struct RBTreeNode
{
	T _data;

	RBTreeNode<T>* _left;
	RBTreeNode<T>* _right;
	RBTreeNode<T>* _parent;
	Colour _col;


	RBTreeNode(const T& data)
		:_data(data)
		, _left(nullptr)
		, _right(nullptr)
		, _parent(nullptr)
	{}
};

template<class T, class Ref, class Ptr>
struct RBTreeIterator
{
	typedef RBTreeNode<T> Node;
	typedef RBTreeIterator<T> Self;

	Node* _node;

	RBTreeIterator(Node* node)
		:_node(node)
	{}

	Self& operator++()
	{
		if (_node->_right != 0)
		{  
			//右不为空
			// ++下一个要访问的是：
			// 右子树最左结点就是中序第一个（即：右子树最小的那一个）
			Node* leftMost = _node->_right;
			while (leftMost->_left)
			{
				leftMost = leftMost->_left;
			}
			_node = leftMost;
		}
		else
		{
			//右子树为空（代表当前节点所在的子树访问完了）
			//沿着根节点的路径查找，孩子是父亲左的那个祖先结点
			//就是要访问的结点
			Node* cur = _node;
			Node* parent = cur->_parent;
			while (parent && cur == parent->_right)
			{
				cur = parent;
				parent = cur->_parent;
			}
			_node=parent;
		}

		return *this;
	}
	
	Self& operator--()
	{
		if (_node == nullptr)//end()
		{  
			//左子树不为空，
			// --下一个要访问的是：
			// 中序左子树最后一个（即：左子树最大的那一个）
			Node* rightMost = _node;
			while (rightMost && rightMost->_right)
			{
				// --end()，特殊处理，走到中序最后一个节点，整棵树的最右节点
				rightMost = rightMost->_right;
			}
			_node = rightMost;
		}
		else if(_node->_left)
		{
			// 左子树不为空，中序左子树最后一个
			Node* rightMost = _node->_left;
			while (rightMost->_right)
			{
				rightMost = rightMost->_right;
			}
			_node = rightMost;
		}
		else
		{
			Node* cur = _root;
			Node* parent = cur->_parent;
			while (parent && cur == parent->_left)
			{
				cur = parent;
				parent = cur->_parent;
			}
			_node = parent;
		}

		return *this;
	}

	Ref operator*()
	{
		return _node->_data;
	}

	Ptr operator->()
	{
		return &_node->_data;
	}

	bool operator!=(const Self& s)
	{
		return _node != s._node;
	}
	
	bool operator==(const Self& s)
	{
		return _node == s._node;
	}
};


//  Key  K: 给Find、Erase使用
// pair<K,V>  T: 给Insert 结点使用

template<class K, class T, class KeyOfT>// T 传什么，Node就是什么类型
class RBTree                            // KeyOfT 为了取pair的key（first）进行插入的比较
{
	typedef RBTreeNode<T> Node;
public:
	typedef RBTreeIterator<T> Iterator;

	Iterator Begin()
	{
		Node* leftMost = _root;
		while (leftMost && leftMost->_left)
		{
			leftMost = leftMost->_left;
		}
		return Iterator(leftMost);
	}

	Iterator End()
	{
		return Iterator(nullptr);
	}

	RBTree() = default;

	//RBTree(const RBTree<K, T, KeyOfT>& t)
	RBTree(const RBTree& t)//类里面可以简写（不写模板参数），类外不可以
	{
		_root = Copy(t._root);
	}

	//RBTree<K, T, KeyOfT>& operator=(RBTree<K, T, KeyOfT> t)
	RBTree& operator=(RBTree t)
	{
		swap(_root, t._root);
		return *this;
	}

	~RBTree()
	{
		Destory(_root);
		_root = nullptr;
	}

	// 在AVL树中插入值为kv的节点
	pair<Iterator, bool> Insert(const T& data)
	{
		if (_root == nullptr)
		{
			_root = new Node(data);
			return true;
		}

		KeyOfT kot;// 生成KeyOfT的对象

		Node* parent = nullptr;
		Node* cur = _root;
		while (cur)
		{
			//if (cur->_data < data) // 当data是一个key时，不影响，当为pair<K,V>时，如何处理？
			                       // pair比较大小是按照，first比完，second再比，first小就小，first不小，second小就小
				                   // second加入了比较逻辑，不符合，如何处理？
				                   // 是key直接比较，是pair取first来比较
				                   // 通过仿函数把 type_value 里面的key取出来，然后用key统一取支持比较
			
			if (kot(cur->_data) < kot(data))//若data本身就是key,就返回key
			{                               //若data是pair，就返回pair的first
				parent = cur;
				cur = cur->_right;
			}
			else if (kot(cur->_data) > kot(data))
			{
				parent = cur;
				cur = cur->_left;
			}
			else
			{
				//找到相同的数，返回false
				return make_pair(Iterator(cur,_root),false);
			}
		}
		//插入新节点，颜色给红色
		cur = new Node(data);
		cur->_col = RED;
		if (kot(parent->_data) < kot(data))
		{
			parent->_right = cur;
		}
		else
		{
			parent->_left = cur;
		}
		cur->_parent = parent;//与parent链接

		while (parent && parent->_col == RED)//父亲存在且为红
		{
			//     g
			//  p     u
			//不关注c插入在p的左/右方向
			Node* grandfather = parent->_parent;
			if (parent == grandfather->_left)//
			{
				//u存在且为红->变色再继续往上更新
				Node* uncle = grandfather->_right;
				if (uncle && uncle->_col == RED)//u 存在且为红
				{
					parent->_col = uncle->_col = BLACK;// p、u变为黑
					grandfather->_col = RED;//g变为红

					//继续往上更新
					cur = grandfather;
					parent = cur->_parent;
				}
				else
				{
					//u存在且为黑 或 不存在 -> 旋转 + 变色
					// 关注c插入在p的左/右方向
						//    g
					   //  p     u
					  // c
					  // 单旋
					if (cur == parent->_left)
					{
						RotateR(grandfather);
						parent->_col = BLACK;
						grandfather->_col = RED;
					}
					else
					{
						//    g
					   //  p     u
					  //     c
					  //双旋
						RotateL(parent);
						RotateR(grandfather);
						cur->_col = BLACK;
						grandfather->_col = RED;
					}

					break;
				}
			}
			else//parent == grandfather->_right
			{
				//     g
				//  u     p 
				//不关注c插入在p的左/右方向

				Node* uncle = grandfather->_left;
				if (uncle && uncle->_col == RED)
				{
					parent->_col = uncle->_col = BLACK;
					grandfather->_col = RED;

					//继续往上更新
					cur = grandfather;
					parent = cur->_parent;
				}
				else
				{
					//u存在且为黑 或 不存在 -> 旋转 + 变色
					// 关注c插入在p的左/右方向
					//    g
				   //  u     p
				  //           c
				  // 单旋
					if (cur == parent->_right)
					{
						RotateL(grandfather);
						parent->_col = BLACK;
						grandfather->_col = RED;
					}
					else
					{
						//    g
					   //  u     p
					  //       c
					  //双旋
						RotateR(parent);
						RotateL(grandfather);
						cur->_col = BLACK;
						grandfather->_col = RED;
					}

					break;
				}
			}
		}
		//1、parent不存在，cur就是根了，出去之后把根处理成黑的
		//2、parent存在，且为黑
		//3、parent存在，且为红，继续循环处理

		_root->_col = BLACK;//无论什么情况都把根变黑

		return make_pair(Iterator(newnode,_root),true);
	}

	Iterator Find(const K& key)  // set:K可直接查找
	{                         // map：要取pair<K,V>，里的first来进行查找
		Node* cur = _root;
		while (cur)
		{
			if (cur->_kv.first < key)
			{
				cur = cur->_right;
			}
			else if (cur->_kv.first > key)
			{
				cur = cur->_left;
			}
			else
			{
				return Iterator(cur,_root);
			}
		}
		return End();
	}

	int Height()
	{
		return _Height(_root);
	}

	void InOrder()
	{
		_InOrder(_root);
		cout << endl;
	}

	int Size()
	{
		return _Size(_root);
	}

	bool IsBalance()
	{
		if (_root == nullptr)
		{
			return true;
		}

		if (_root->_col == RED)
		{
			return false;
		}

		//找一条路径作为参考值（最左路径 或 最右路径）
		int refNum = 0;
		Node* cur = _root;
		while (cur)
		{
			if (cur->_col == BLACK)
			{
				++refNum;
			}

			cur = cur->_left;//走最左路径
		}

		return Check(_root, 0, refNum);
	}

private:
	bool Check(Node* root, int blackNum, const int refNum)
	{
		if (root == nullptr)//结束条件
		{
			cout << blackNum << endl;
			if (refNum != blackNum)
			{
				cout << "存在黑色节点的数量不相等的路径" << endl;
				return false;
			}

			return true;
		}

		if (root->_col == RED && root->_parent->_col == RED)
		{
			cout << root->_kv.first << "存在连续的红色节点" << endl;
			return false;
		}

		if (root->_col == BLACK)
		{
			blackNum++;
		}

		//前序遍历
		return Check(root->_left, blackNum, refNum)
			&& Check(root->_right, blackNum, refNum);
	}


	int _Size(Node* root)
	{
		//左边+右边
		return root == nullptr ? 0 : _Size(root->_left) + _Size(root->_right) + 1;
	}

	void _InOrder(Node* root)
	{
		if (root == nullptr)
		{
			return;
		}

		_InOrder(root->_left);
		cout << root->_kv.first << ":" << root->_kv.second << endl;
		_InOrder(root->_right);
	}

	int _Height(Node* root)
	{
		if (root == nullptr)
		{
			return 0;
		}
		int leftHeight = _Height(root->_left);
		int rightHeight = _Height(root->_right);

		return leftHeight > rightHeight ? leftHeight + 1 : rightHeight + 1;
	}

	// 右单旋
	void RotateR(Node* parent)
	{
		Node* subL = parent->_left;
		Node* subLR = subL->_right;

		parent->_left = subLR;
		if (subLR)
			subLR->_parent = parent;

		Node* parentParent = parent->_parent;

		subL->_right = parent;
		parent->_parent = subL;

		//判断是否为根？
		if (parentParent == nullptr)
		{
			_root = subL;
			subL->_parent = nullptr;
		}
		else
		{
			if (parent == parentParent->_left)
			{
				parentParent->_left = subL;
			}
			else
			{
				parentParent->_right = subL;
			}

			subL->_parent = parentParent;
		}
	}

	// 左单旋
	void RotateL(Node* parent)
	{
		Node* subR = parent->_right;
		Node* subRL = subR->_left;

		parent->_right = subRL;
		if (subRL)
			subRL->_parent = parent;

		Node* parentParent = parent->_parent;

		subR->_left = parent;
		parent->_parent = subR;

		if (parentParent == nullptr)
		{
			_root = subR;
			subR->_parent = nullptr;
		}
		else
		{
			if (parent == parentParent->_left)
			{
				parentParent->_left = subR;
			}
			else
			{
				parentParent->_right = subR;
			}
			subR->_parent = parentParent;
		}
	}

	void Destory(Node* root)
	{
		if (root == nullptr)
			return;

		Destory(root->_left);
		Destory(root->_right);
		
		delete root;
	}

	Node* Copy(Node* root)
	{
		if (root == nullptr)
			return nullptr;

		Node* newRoot = new Node(root->_data);
		newRoot->_left = Copy(root->_left);
		newRoot->_right = Copy(root->_right);

		return newRoot;
	}

private:
	Node* _root = nullptr;
};
